package client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * This Thread accepts user input and send it to the server.
 * 
 * @author Lukas
 *
 */
public class InputSender implements Runnable {
	private final Socket socket;
    private final PrintWriter out;
    private final BufferedReader in;
    private final int udpPort;
    private final MessageReceiver receiver;

	/**
	 * Constructor
	 * @param host The host.
	 * @param port The TCP-port.
	 * @param udpPort The UDP-port.
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public InputSender(String host, int port, int udpPort) throws UnknownHostException, IOException {
		socket = new Socket(host, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.udpPort = udpPort;
        receiver = new MessageReceiver(udpPort);
        (new Thread(receiver)).start();
	}
	
	@Override
	public void run() {
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String command;
        try {
        	while ((command = stdIn.readLine()) != null) {
        		Scanner sc = new Scanner(command);
        		String s;
        		try {
        			s = sc.next();
        		} catch (NoSuchElementException e) {
        			continue;
        		}
        		if (s.equals("!login")) {
        			command += " " + udpPort;
        			synchronized (receiver.user) {
        				out.println(command);
        				receiver.user = in.readLine();
        			}
        		} else {
        			out.println(command);
        		}
        	    String response = in.readLine();
        	    if (response == null) {
        	    	throw new IOException();
        	    }
        	    while (!response.equals("!eof")) {
        	    	System.out.println(response);
        	    	response = in.readLine();
        	    }
        	    System.out.print(in.readLine());
        	    if (s.equals("!end")) {
        	    	break;
        	    }
        	}
        } catch (IOException e) {
        	System.err.println("Could not read command from console");
        }
        receiver.shutdown();
        out.close();
        try {
			stdIn.close();
		} catch (IOException e) {
			System.err.println("Could not close command line reader");
		}
        try {
			socket.close();
		} catch (IOException e) {
			System.err.println("Could not close socket");
		}
	}

}
